package cn.yuanqiao.archive.wenjianzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantMijiComparisonTableService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.ILixianjieshouService;
import cn.yuanqiao.archive.wenjianzhengli.service.ITenantYqdaDocumentService;
import cn.yuanqiao.archive.xiaoxitongzhi.domain.YqXxtz;
import cn.yuanqiao.archive.xiaoxitongzhi.mapper.YqXxtzMapper;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.ListUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.sql.YqDatabaseSQLUtil;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.system.service.ISysDeptService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zjj
 * @date 2023/6/25
 */
@Service
public class LixianjieshouServiceImpl implements ILixianjieshouService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private ITenantYqdaDocumentService documentService;
    @Autowired
    private TenantYqdaDocumentMapper documentMapper;
    @Autowired
    private TenantYqItemMapper itemMapper;
    @Autowired
    private TenantItemFolderMapper itemFolderMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantYqdaFolderMapper yqdaFolderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private TenantMdataListMapper mdataListMapper;

    @Autowired
    private TenantCateMdataListMapper cateMdataListMapper;
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private YqXxtzMapper yqXxtzMapper;
    @Autowired
    private ITenantMijiComparisonTableService iTenantMijiComparisonTableService;

    @Value("${FBswitch}")
    private boolean FBswitch;
    /**
     * 添加项目
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int addItem(JSONObject object) {
        //{categoryId:111,column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        JSONArray array = object.getJSONArray("column");
        Map<String, String> column = new HashMap<>();
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        //验证是否存在数据
        int itemCount = archiveMapper.getCountByMap(column, category.getItemTableName());
        if (itemCount > 0) {
            throw new ServiceException("数据重复，请检查后提交！");
        }
        //特殊字符验证
        SpecialCharacter(category.getGroupId(), 3, column);

        Long id = SnowflakeIdGenerator.generateId();
        //column.put("QZH", category.getFondsCode());
        column.putAll(addCommonCol(column, category, 3));

        column.put("ID", String.valueOf(id));
        TenantYqItem item = new TenantYqItem();
        item.setColNames(column);
        item.setTableName(category.getItemTableName());
        itemMapper.insertItemDisperse(item); //插入分表

        column.put("SUB_TABLE_NAME", category.getItemTableName());
        column.remove("ID");
        column.put("ITEM_ID", String.valueOf(id));
        item.setColNames(column);
        item.setTableName(new TenantYqItem().getTableName());
        int r = itemMapper.insertItem(item); //插入总表
        return r;
    }

    /**
     * 组项目
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int mergeFolder(JSONObject object) {
        //{categoryId:111,folderIds:"111,222",column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        //验证需要合并卷的 是否是可以合并的
        TenantItemFolder itemFolder = new TenantItemFolder();
        String folderIdsStr = object.getString("folderIds");
        int num = itemFolderMapper.getCountByFolderIds(folderIdsStr, itemFolder.getTableName());
        if (num == 0) {
            Long categoryId = object.getLong("categoryId");
            TenantCategory category = new TenantCategory();
            category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());

            //验证卷是不是一个项目下的
            List<Long> itemYqda = yqdaFolderMapper.getItemIdByFolderId(folderIdsStr, new TenantYqdaFolder().getTableName());
            if (itemYqda != null && itemYqda.size() > 1) {
                throw new ServiceException("选中的案卷不在一个项目下");
            }

            Long itemId = SnowflakeIdGenerator.generateId();
            String[] folderIds = folderIdsStr.split(",");
            //添加关系
            itemFolder.setItemId(itemId);
            for (String folderId : folderIds) {
                itemFolder.setFolderId(Long.valueOf(folderId));
                itemFolderMapper.addItemFolder(itemFolder);
                //修改是否组项目状态
                Map<String, String> IS_PROJECT = new HashMap<>();
                IS_PROJECT.put("IS_PROJECT", "1");
                TenantYqFolder yqFolder = new TenantYqFolder();
                yqFolder.setFolderId(Long.valueOf(folderId));
                yqFolder.setColNames(IS_PROJECT);
                folderMapper.updateYqFolder(yqFolder);
                yqFolder.setTableName(category.getFolderTableName());
                folderMapper.updateYqFolderDisperse(yqFolder);
            }
            JSONArray array = object.getJSONArray("column");
            Map<String, String> column = new HashMap<>();
            for (int j = 0; j < array.size(); j++) {
                JSONObject data = array.getJSONObject(j);
                column.put(data.getString("name"), data.getString("value"));
            }
            //验证是否存在数据
            int itemCount = archiveMapper.getCountByMap(column, category.getItemTableName());
            if (itemCount > 0) {
                throw new ServiceException("数据重复，请检查后提交！");
            }
            //验证特殊字符
            SpecialCharacter(category.getGroupId(), 3, column);

            column.putAll(addCommonCol(column, category, 3));
            column.put("ID", String.valueOf(itemId));
            TenantYqItem item = new TenantYqItem();
            item.setColNames(column);
            item.setTableName(category.getItemTableName());
            itemMapper.insertItemDisperse(item); //插入分表

            column.put("SUB_TABLE_NAME", category.getItemTableName());
            column.remove("ID");
            column.put("ITEM_ID", String.valueOf(itemId));
            item.setColNames(column);
            item.setTableName(new TenantYqItem().getTableName());
            int r = itemMapper.insertItem(item); //插入总表

            //根据关联关系 修改操作
            //项目层
            relevanceMap(category, 3, itemId, folderIdsStr);
            for (String folderId : folderIds) {
                List<String> daIdss = yqdaFolderMapper.selectFileIdByFolderId(String.valueOf(folderId), new TenantYqdaFolder().getTableName());
                //更新卷
                relevanceMap(category, 1, Long.valueOf(folderId), String.join(",", daIdss));
            }


            return r;
        } else {
            throw new ServiceException("选中的案卷已有关联项目");
        }
    }

    /**
     * 添加卷
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public TenantYqFolder addFolder(JSONObject object) {
        //{categoryId:111,itemId:123,column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Long folderId = SnowflakeIdGenerator.generateId();
        Map<String, String> column = new HashMap<>();
        //添加关联关系
        Long itemId = null;
        if (category.getType() == 3) {
            if (object.containsKey("itemId") && StringUtils.isNotEmpty(object.getString("itemId"))) {
                itemId = object.getLong("itemId");
                TenantItemFolder itemFolder = new TenantItemFolder();
                itemFolder.setItemId(itemId);
                itemFolder.setFolderId(folderId);
                itemFolderMapper.addItemFolder(itemFolder);
                //已组项目
                column.put("IS_PROJECT", "1");
            } else {
                //未组项目
                column.put("IS_PROJECT", "0");
            }
        }
        //添加卷信息
        JSONArray array = object.getJSONArray("column");
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        //验证是否存在数据
        int itemCount = archiveMapper.getCountByMap(column, category.getFolderTableName());
        if (itemCount > 0) {
            throw new ServiceException("数据重复，请检查后提交！");
        }
        //验证特殊字符
        SpecialCharacter(category.getGroupId(), 1, column);

        column.putAll(addCommonCol(column, category, 1));

        column.put("ID", String.valueOf(folderId));
        TenantYqFolder folder = new TenantYqFolder();
        folder.setColNames(column);
        folder.setTableName(category.getFolderTableName());
        folderMapper.insertYqFolderDisperse(folder); //插入分表

        column.put("SUB_TABLE_NAME", category.getFolderTableName());
        column.remove("ID");
        column.put("FOLDER_ID", String.valueOf(folderId));
        folder.setColNames(column);
        folder.setTableName(new TenantYqFolder().getTableName());
        int r = folderMapper.insertYqFolder(folder); //插入总表

        //插入卷和件的关系
        if (object.containsKey("daIds") && StringUtils.isNotEmpty(object.getString("daIds"))) {
            String[] daIds = object.getString("daIds").split(",");
            for (String daId : daIds) {
                //更新组卷状态
                Map<String, String> columnDa = new HashMap<>();
                columnDa.put("IS_ZUJUAN", "1");
                TenantYqda tenantYqda = new TenantYqda();
                tenantYqda.setTableName(category.getFileTableName());
                tenantYqda.setColNames(columnDa);
                tenantYqda.setDaId(Long.valueOf(daId));
                yqdaMapper.updateYqdaDisperse(tenantYqda);
                tenantYqda.setTableName(new TenantYqda().getTableName());
                yqdaMapper.updateYqda(tenantYqda);

                TenantYqdaFolder yqdaFolder = yqdaFolderMapper.selectByDaId(Long.valueOf(daId), new TenantYqdaFolder().getTableName());
                if (yqdaFolder != null) {
                    yqdaFolder.setFolderId(folderId);
                    yqdaFolderMapper.updateByDaId(yqdaFolder);
                } else {
                    yqdaFolderMapper.addYqdaFolder(yqdaFolder);
                }
            }
        }
        //根据关联关系 修改操作
        if (object.containsKey("daIds") && StringUtils.isNotEmpty(object.getString("daIds"))) {
            relevanceMap(category, 1, folderId, object.getString("daIds"));
        } else {
            relevanceMap(category, 1, folderId, null);
        }
        if (itemId != null) {
            List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId), new TenantItemFolder().getTableName());
            relevanceMap(category, 3, itemId, String.join(",", folderIds));
        }


        return folder;
    }

    /**
     * 合并卷
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int assemblyFolder(JSONObject object) {
        //{categoryId:111,folderIds:"111,222",column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        String folderIdsStr = object.getString("folderIds");
        //是项目门类的话 选择的卷必须是一个项目下的
        Long itemId = null;
        if (category.getType() == 3) {
            List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(folderIdsStr, category.getItemTableName(), new TenantItemFolder().getTableName());
            if (itemIds.size() > 0) {
                itemId = hasDuplicates(itemIds);
                if (itemId == null) {
                    throw new ServiceException("选择的卷不在一同个项目下，不能合并卷！");
                }
            }
        }

        //添加卷信息
        JSONArray array = object.getJSONArray("column");
        Map<String, String> column = new HashMap<>();
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        ;
        if (null != object.getString("fromygd") && "true".equals(object.getString("fromygd"))) {
            column.put("STATE", "10");
        }
        //验证特殊字符
        SpecialCharacter(category.getGroupId(), 1, column);

        column.putAll(addCommonCol(column, category, 1));

        //验证密级 件的密级不能大于卷的密级
        Integer maxJianMj = yqdaMapper.getMaxJianMjByFolderIds(folderIdsStr, category.getFileTableName(), new TenantYqdaFolder().getTableName());
        if (maxJianMj != null && column.get("MJ") != null && !"".equals(String.valueOf(column.get("MJ")))) {
            Integer juanMj = Integer.valueOf(column.get("MJ"));
            if (maxJianMj > juanMj) {
                throw new ServiceException("选中的卷内件中密级不能大于卷的密级！");
            }
        }


        //修改卷内件的关联关系
        Long folderId = SnowflakeIdGenerator.generateId();
        TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();

        yqdaFolderMapper.updateFolderIdByFolderId(folderIdsStr, folderId, yqdaFolder.getTableName());


        //删除合并的档案
        logger.info("-----注意开始删除档案-----delete folder by ids=" + folderIdsStr);
        //删除主表
        folderMapper.delFolderByIds(folderIdsStr, yqdaFolder.getTableName());
        //删除分表
        folderMapper.delFolderDisperseByIds(folderIdsStr, category.getFolderTableName());


        //已组项目
        if (category.getType() == 3 && itemId != null) {
            column.put("IS_PROJECT", "1");
        }


        column.put("ID", String.valueOf(folderId));
        TenantYqFolder folder = new TenantYqFolder();
        folder.setColNames(column);
        folder.setTableName(category.getFolderTableName());
        folderMapper.insertYqFolderDisperse(folder); //插入分表

        column.put("SUB_TABLE_NAME", category.getFolderTableName());
        column.remove("ID");
        column.put("FOLDER_ID", String.valueOf(folderId));
        folder.setColNames(column);
        folder.setTableName(new TenantYqFolder().getTableName());
        int r = folderMapper.insertYqFolder(folder); //插入总表
        //插入关联关系
        if (category.getType() == 3 && itemId != null) {
            TenantItemFolder itemFolder = new TenantItemFolder();
            itemFolder.setItemId(itemId);
            itemFolder.setFolderId(folderId);
            itemFolderMapper.addItemFolder(itemFolder);
        }
        //根据关联关系 修改操作
        List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(String.valueOf(folderId), new TenantYqdaFolder().getTableName());
        relevanceMap(category, 1, folderId, String.join(",", daIds));
        if (category.getType() == 3 && itemId != null) {
            List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId), new TenantItemFolder().getTableName());
            relevanceMap(category, 3, itemId, String.join(",", folderIds));
        }

        return r;
    }

    /**
     * 验证是否可以合并卷
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public Boolean assemblyFolderVerify(JSONObject object) {
        Boolean bl = true;
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        String folderIdsStr = object.getString("folderIds");
        //是项目门类的话 选择的卷必须是一个项目下的
        Long itemId = null;
        if (category.getType() == 3) {
            List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(folderIdsStr, category.getItemTableName(), new TenantItemFolder().getTableName());
            if (itemIds.size() > 0) {
                itemId = hasDuplicates(itemIds);
                if (itemId == null) {
                    bl = false;
                }
            }
        }
        return bl;
    }

    /**
     * 验证是否有重复数据
     *
     * @param list
     * @return
     */
    private Long hasDuplicates(List<Long> list) {
        Set<Long> set = new HashSet<>();
        for (Long value : list) {
            set.add(value);
        }
        if (set.size() == 1) {
            Long[] array = set.toArray(new Long[set.size()]);
            return array[0];
        } else {
            return null;
        }

    }

    /**
     * 拆卷
     *
     * @param object
     * @return
     */
    @Override
    public int splitFolder(JSONObject object) {
        //{"categoryId":"123",folderIds:"111,222"}
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());


        String folderIds = object.getString("folderIds");
        //查询卷内件ID
        List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(folderIds, new TenantYqdaFolder().getTableName());
        logger.info("-----注意开始删除档案-----delete folder by ids=" + folderIds);
        //删除主卷表
        TenantYqFolder folder = new TenantYqFolder();
        folderMapper.delFolderByIds(folderIds, folder.getTableName());
        //删除分卷表
        int r = folderMapper.delFolderDisperseByIds(folderIds, category.getFolderTableName());
        //删除卷和项目的关系
        List<Long> item = null;
        if (category.getType() == 3) {
            //如果件和项目有关系，把卷ID置为空
            item = yqdaFolderMapper.getItemIdByFolderId(folderIds, new TenantItemFolder().getTableName());
            if (item != null && item.size() > 0) {
                //yqdaFolderMapper.setItemIdNullByFolderId(folderIds,new TenantYqdaFolder().getTableName());
            } else {
                itemFolderMapper.deleteItemFolderByFolderId(folderIds, new TenantItemFolder().getTableName());
            }
        }

        //修改是否已组卷
        for (String daId : daIds) {
            Map<String, String> IS_PROJECT = new HashMap<>();
            IS_PROJECT.put("IS_ZUJUAN", "0");
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(IS_PROJECT);
            yqda.setDaId(Long.valueOf(daId));
            yqdaMapper.updateYqda(yqda);
            yqda.setTableName(category.getFileTableName());
            yqdaMapper.updateYqdaDisperse(yqda);
        }

        //删除关联关系
        TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
        yqdaFolderMapper.setFolderIdNullByFolderIds(folderIds, yqdaFolder.getTableName());

        if (category.getType() == 3) {
            //这里更新的是项目层
            if (item != null && item.size() > 0) {
                for (Long id : item) {
                    List<String> fodlerIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(id), new TenantItemFolder().getTableName());
                    relevanceMap(category, 3, id, String.join(",", fodlerIds));
                }

            }
        }
        return r;
    }

    /**
     * 拆项目
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int splitItem(JSONObject object) {
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        String itemIds = object.getString("itemIds");
        //查询项目内卷ID
        TenantItemFolder itemFolder = new TenantItemFolder();
        List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(itemIds, itemFolder.getTableName());
        logger.info("-----注意开始删除档案-----delete item by ids=" + itemIds);
        //删除主项目表
        TenantYqItem yqItem = new TenantYqItem();
        itemMapper.delItemByIds(itemIds, yqItem.getTableName());
        //删除分项目表
        int r = itemMapper.delItemDisperseByIds(itemIds, category.getItemTableName());
        //删除卷和项目的关系
        itemFolderMapper.deleteItemFolderByItemId(itemIds, itemFolder.getTableName());
        //修改是否已组项目
        for (String folderId : folderIds) {
            Map<String, String> IS_PROJECT = new HashMap<>();
            IS_PROJECT.put("IS_PROJECT", "0");
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(IS_PROJECT);
            folder.setFolderId(Long.valueOf(folderId));
            folderMapper.updateYqFolder(folder);
            folder.setTableName(category.getFolderTableName());
            folderMapper.updateYqFolderDisperse(folder);
            //修改件和项目关联
            yqdaFolderMapper.setItemIdNullByFolderId(folderId, new TenantYqdaFolder().getTableName());
        }
        return r;
    }

    /**
     * 移除卷和项目关系
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int delItemFolderByFolderId(JSONObject object) {
        Long categoryId = object.getLong("categoryId");
        String folderIds = object.getString("folderIds");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        String[] folderIdss = folderIds.split(",");
        for (String folderId : folderIdss) {
            Map<String, String> IS_PROJECT = new HashMap<>();
            IS_PROJECT.put("IS_PROJECT", "0");
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(IS_PROJECT);
            folder.setFolderId(Long.valueOf(folderId));
            folderMapper.updateYqFolder(folder);
            folder.setTableName(category.getFolderTableName());
            folderMapper.updateYqFolderDisperse(folder);
        }
        List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(folderIds, category.getItemTableName(), new TenantItemFolder().getTableName());
        int r = itemFolderMapper.deleteItemFolderByFolderId(folderIds, new TenantItemFolder().getTableName());
        for (Long itemId : itemIds) {
            //修改项目层
            List<String> folderIdStr = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId), new TenantItemFolder().getTableName());
            relevanceMap(category, 3, itemId, String.join(",", folderIdStr));
        }

        return r;
    }

    /**
     * 绑定卷和件的关系
     *
     * @param object
     */
    @Override
    public void bindFolderIdDaId(JSONObject object) {
        Long folderId = object.getLong("folderId");
        String[] daIds = object.getString("daIds").split(",");
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        for (String daId : daIds) {
            //更新组卷状态
            Map<String, String> columnDa = new HashMap<>();
            columnDa.put("IS_ZUJUAN", "1");
            TenantYqda tenantYqda = new TenantYqda();
            tenantYqda.setTableName(category.getFileTableName());
            tenantYqda.setColNames(columnDa);
            tenantYqda.setDaId(Long.valueOf(daId));
            yqdaMapper.updateYqdaDisperse(tenantYqda);
            tenantYqda.setTableName(new TenantYqda().getTableName());
            yqdaMapper.updateYqda(tenantYqda);

            TenantYqdaFolder yqdaFolder = yqdaFolderMapper.selectByDaId(Long.valueOf(daId), new TenantYqdaFolder().getTableName());
            if (yqdaFolder != null) {
                yqdaFolder.setFolderId(folderId);
                yqdaFolderMapper.updateByDaId(yqdaFolder);
            } else {
                yqdaFolderMapper.addYqdaFolder(yqdaFolder);
            }
        }

        List<String> daIdss = yqdaFolderMapper.selectFileIdByFolderId(String.valueOf(folderId), new TenantYqdaFolder().getTableName());
        //更新卷
        relevanceMap(category, 1, folderId, String.join(",", daIdss));

        if (category.getType() == 3) {
            //更新项目
            List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(String.valueOf(folderId), category.getFolderTableName(), new TenantItemFolder().getTableName());
            if (itemIds != null && itemIds.size() > 0) {
                for (Long itemId : itemIds) {
                    List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId), new TenantItemFolder().getTableName());
                    relevanceMap(category, 3, itemId, String.join(",", folderIds));
                }

            }
        }
    }

    @Override
    public int tuihui(Long categoryId, Long[] ids) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, String> column = new HashMap<>();
        column.put("IS_INDEX", "1");
        column.put("STATE", "2");
        //处理项目层
        if (category.getType() == 3) {
            for (Long id : ids) {
                Map<String, Object> data = itemMapper.getItemById("JS_TYPE", id, category.getItemTableName());
                column.put("JS_TYPE", getJsTypeByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                //修改项目
                TenantYqItem item = new TenantYqItem();
                item.setColNames(column);
                item.setItemId(id);
                itemMapper.updateItem(item); //主表
                item.setTableName(category.getItemTableName());
                itemMapper.updateItemDisperse(item);  //分表

                //修改卷
                Long[] itemId = new Long[]{id};
                Long[] folderIds = folderMapper.getFolderIdsByItemIds(itemId, category.getFolderTableName(), new TenantItemFolder().getTableName());
                for (Long folderId : folderIds) {

                    Map<String, Object> boxState = folderMapper.getYqFolderById("BOXSTATE", folderId, category.getFolderTableName());
                    if (boxState != null && "1".equals(boxState.get("BOXSTATE"))) {
                        throw new ServiceException("选择的档案已装盒，不能退回！");
                    }

                    TenantYqFolder yqFolder = new TenantYqFolder();
                    yqFolder.setColNames(column);
                    yqFolder.setFolderId(folderId);
                    folderMapper.updateYqFolder(yqFolder);
                    yqFolder.setTableName(category.getFolderTableName());
                    folderMapper.updateYqFolderDisperse(yqFolder);
                }

                //修改件
                Long[] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds, category.getFileTableName(), new TenantYqdaFolder().getTableName());
                for (Long daId : daIds) {
                    TenantYqda yqda = new TenantYqda();
                    yqda.setColNames(column);
                    yqda.setDaId(daId);
                    yqdaMapper.updateYqda(yqda);
                    yqda.setTableName(category.getFileTableName());
                    yqdaMapper.updateYqdaDisperse(yqda);
                }
            }
        } else if (category.getType() == 1) {
            //处理组卷
            for (Long folderId : ids) {
                Map<String, Object> boxState = folderMapper.getYqFolderById("BOXSTATE", folderId, category.getFolderTableName());
                if (boxState != null && "1".equals(boxState.get("BOXSTATE"))) {
                    throw new ServiceException("选择的档案已装盒，不能退回！");
                }
                Map<String, Object> data = folderMapper.getYqFolderById("JS_TYPE", folderId, category.getFolderTableName());
                column.put("JS_TYPE", getJsTypeByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                //修改卷
                TenantYqFolder yqFolder = new TenantYqFolder();
                yqFolder.setColNames(column);
                yqFolder.setFolderId(folderId);
                folderMapper.updateYqFolder(yqFolder);
                yqFolder.setTableName(category.getFolderTableName());
                folderMapper.updateYqFolderDisperse(yqFolder);

                //修改件
                Long[] folderIds = new Long[]{folderId};
                Long[] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds, category.getFileTableName(), new TenantYqdaFolder().getTableName());
                for (Long daId : daIds) {
                    TenantYqda yqda = new TenantYqda();
                    yqda.setColNames(column);
                    yqda.setDaId(daId);
                    yqdaMapper.updateYqda(yqda);
                    yqda.setTableName(category.getFileTableName());
                    yqdaMapper.updateYqdaDisperse(yqda);
                }
            }
        } else if (category.getType() == 0) {
            //处理组件
            for (Long daId : ids) {
                Map<String, Object> boxState = yqdaMapper.getYqdaById("BOXSTATE", daId, category.getFileTableName());
                if (boxState != null && "1".equals(boxState.get("BOXSTATE"))) {
                    throw new ServiceException("选择的档案已装盒，不能退回！");
                }

                Map<String, Object> data = yqdaMapper.getYqdaById("JS_TYPE", daId, category.getFileTableName());
                column.put("JS_TYPE", getJsTypeByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(column);
                yqda.setDaId(daId);
                yqdaMapper.updateYqda(yqda);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.updateYqdaDisperse(yqda);
            }
        }

        return 1;
    }

    /**
     * 提交
     *
     * @param categoryId
     * @param idList
     */
    @Override
    @Transactional
    public void submitButton(Long categoryId, List<String> idList) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
//        categoryMapper.selectItem(i)
        Long userId = null;
        for (String id : idList) {
            TenantYqdaFolder yf = new TenantYqdaFolder();
            yf = yqdaFolderMapper.selectByDaId(Long.valueOf(id), yf.getTableName());
            if (yf == null) {
                continue;
            }
            Map<String, Object> map = itemMapper.selectBtCreateBy(yf.getItemId(), category.getItemTableName());
            if (userId == null) {
                userId = (Long) map.get("CREATE_ID");
                System.out.println();
            }
            TenantYqda yqda = new TenantYqda();
            Map<String, String> column = new HashMap<>();
//            column.put("ID",id);
            column.put("CREATE_BY", map.get("CREATE_BY").toString());
            column.put("CREATE_ID", String.valueOf(map.get("CREATE_ID")));
            yqda.setColNames(column);
            yqda.setTableName(category.getFileTableName());
            yqda.setDaId(Long.valueOf(id));
            yqdaMapper.updateYqdaDisperse(yqda); //修改分表

            yqda.setTableName(new TenantYqda().getTableName());
            int r = yqdaMapper.updateYqda(yqda); //修改总表
        }
        // 添加通知消息
        addMsg(idList,userId);

    }

    private void addMsg(List<String> pevo, Long userId) {
        YqXxtz yqXxtz = new YqXxtz();
        long id = SnowflakeIdGenerator.generateId();
        yqXxtz.setId(id);
        yqXxtz.setMsg("您有几（" + pevo.size() + "）条待组卷的数据，请尽快整理。");
        yqXxtz.setType(6);
        yqXxtz.setIsRead(0);
        yqXxtz.setRecipientsId(userId);
        yqXxtz.setPublisherId(SecurityUtils.getUserId());
        yqXxtz.setCreateTime(DateUtils.getNowDate());
        yqXxtzMapper.addYqXxtz(yqXxtz);
        yqXxtzMapper.addYqXxfbfw(yqXxtz);
    }

    @Override
    public int updateBgqx(String bgqxVal, String idStr, String type, Long categoryId) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, String> bgqx = new HashMap<>();
        bgqx.put("BGQX", bgqxVal);
        String[] strArray = idStr.split(",");
        Long[] ids = Arrays.stream(strArray)
                .map(Long::valueOf)
                .toArray(Long[]::new);

        List<Long> idList = Arrays.stream(idStr.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());

        int r = 0;
        if ("V".equals(type)) {
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(bgqx);
            folderMapper.updateYqFolderByIds(folder, ids);
            folder.setTableName(category.getFolderTableName());
            r = folderMapper.updateYqFolderDisperseByIds(folder, ids);
        } else if ("F".equals(type)) {
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(bgqx);
            yqdaMapper.updateYqdaByIds(yqda, idList);
            yqda.setTableName(category.getFileTableName());
            r = yqdaMapper.updateYqdaDisperseByIds(yqda, idList);
        }
        return r;
    }

    private String getJsTypeByJsType(int jsType) {
        /**
         * 9 离线接受预归档
         * 10 在线接收预归档
         */
        if (jsType == 9) {
            return "0";
        } else if (jsType == 10) {
            return "1";
        } else {
            throw new ServiceException("未查询到JS_TYPE");
        }
    }

    /**
     * 组卷
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int mergeYqda(JSONObject object) {
        //{categoryId:111,daIds:"111,222",column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        //验证需要合并卷的 是否是可以合并的
        TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
        String daIdsStr = object.getString("daIds");
        int num = yqdaFolderMapper.getCountByDaIds(daIdsStr, yqdaFolder.getTableName());
        if (num == 0) {
            Long categoryId = object.getLong("categoryId");
            TenantCategory category = new TenantCategory();
            category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            //判断件中和项目的关系是否是一个项目下
            List<Long> itemId = yqdaFolderMapper.getItemIdByDaId(daIdsStr, yqdaFolder.getTableName());
            if (itemId != null && itemId.size() > 1) {
                throw new ServiceException("选中的件不在一个项目下！");
            }

            Long folderId = SnowflakeIdGenerator.generateId();
            //添加关系
            String[] daIds = daIdsStr.split(",");
            //添加关系
            yqdaFolder.setFolderId(folderId);
            for (String daId : daIds) {
                yqdaFolder.setDaId(Long.valueOf(daId));
                TenantYqdaFolder tenantYqdaFolder = yqdaFolderMapper.selectByDaId(yqdaFolder.getDaId(), yqdaFolder.getTableName());
                if (tenantYqdaFolder != null) {
                    yqdaFolderMapper.updateByDaId(yqdaFolder);
                } else {
                    if (itemId != null && itemId.size() == 1) {
                        yqdaFolder.setItemId(itemId.get(0));
                    }
                    yqdaFolderMapper.addYqdaFolder(yqdaFolder);
                }
                //修改是否已组卷
                Map<String, String> IS_ZUJUAN = new HashMap<>();
                IS_ZUJUAN.put("IS_ZUJUAN", "1");
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(IS_ZUJUAN);
                yqda.setDaId(Long.valueOf(daId));
                yqdaMapper.updateYqda(yqda);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.updateYqdaDisperse(yqda);
            }

            //添加卷信息
            JSONArray array = object.getJSONArray("column");
            Map<String, String> column = new HashMap<>();
            for (int j = 0; j < array.size(); j++) {
                JSONObject data = array.getJSONObject(j);
                column.put(data.getString("name"), data.getString("value"));
            }
            //验证是否存在数据
            int itemCount = archiveMapper.getCountByMap(column, category.getFolderTableName());
            if (itemCount > 0) {
                throw new ServiceException("数据重复，请检查后提交！");
            }
            //验证特殊字符
            SpecialCharacter(category.getGroupId(), 1, column);

            column.putAll(addCommonCol(column, category, 1));

            //验证密级 件的密级不能大于卷的密级
            Integer maxJianMj = yqdaMapper.getMaxJianMj(daIdsStr, category.getFileTableName());
            if (maxJianMj != null && column.get("MJ") != null && !"".equals(column.get("MJ"))) {
                Integer juanMj = Integer.valueOf(column.get("MJ"));
                if (maxJianMj > juanMj) {
                    throw new ServiceException("选中的件中密级不能大于卷的密级！");
                }
            }
            if (itemId != null && itemId.size() > 0) {
                //已组项目
                column.put("IS_PROJECT", "1");
            } else {
                column.put("IS_PROJECT", "0");
            }
            column.put("ID", String.valueOf(folderId));
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(column);
            folder.setTableName(category.getFolderTableName());
            folderMapper.insertYqFolderDisperse(folder); //插入分表

            column.put("SUB_TABLE_NAME", category.getFolderTableName());
            column.remove("ID");
            column.put("FOLDER_ID", String.valueOf(folderId));
            folder.setColNames(column);
            folder.setTableName(new TenantYqFolder().getTableName());
            int r = folderMapper.insertYqFolder(folder); //插入总表

            //插入项目和卷的关系
            if (itemId != null && itemId.size() == 1) {
                TenantItemFolder itemFolder = new TenantItemFolder();
                itemFolder.setItemId(itemId.get(0));
                itemFolder.setFolderId(folderId);
                itemFolderMapper.addItemFolder(itemFolder);
            }

            //根据关联关系 修改操作
            //更新卷
            relevanceMap(category, 1, folderId, String.join(",", daIds));
            if (category.getType() == 3 && itemId != null && itemId.size() == 1) {
                //更新项目
                List<String> folderIdList = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId.get(0)),new TenantItemFolder().getTableName());
                relevanceMap(category, 3, itemId.get(0), String.join(",", folderIdList));
            }
            return r;
        } else {
            throw new ServiceException("选中的件已有关联卷");
        }

    }

    /**
     * 添加件
     *
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int addYqda(JSONObject object) {
        //{categoryId:111,folderId:123,daId:456,column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        Long categoryId = object.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Long daId = object.getLong("daId");
        //电子文件数默认0
        String eFileCount = "0";
        if (object.containsKey("eFileCount")) {
            eFileCount = object.getString("eFileCount");
        }
        Map<String, String> column = new HashMap<>();
        //添加件信息
        JSONArray array = object.getJSONArray("column");

        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        //验证是否存在数据
        int itemCount = archiveMapper.getCountByMap(column, category.getFileTableName());
        if (itemCount > 0) {
            throw new ServiceException("数据重复，请检查后提交！");
        }
        column.put("EFILE_COUNT", eFileCount);
        //添加关联关系
        if (category.getType() == 1 || category.getType() == 3) {
            TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
            yqdaFolder.setDaId(daId);
            if (category.getType() == 3 && object.containsKey("itemId") && StringUtils.isNotEmpty(object.getString("itemId"))) {
                yqdaFolder.setItemId(object.getLong("itemId"));
            }
            if (object.containsKey("folderId") && StringUtils.isNotEmpty(object.getString("folderId"))) {
                Long folderId = object.getLong("folderId");
                yqdaFolder.setFolderId(folderId);
                if (category.getType() == 3 && yqdaFolder.getItemId() == null) {
                    List<Long> itemId = itemFolderMapper.getItemIdByFolderId(object.getString("folderId"), category.getItemTableName(), new TenantItemFolder().getTableName());
                    if (itemId != null && itemId.size() == 1) {
                        yqdaFolder.setItemId(itemId.get(0));
                    }
                }
                column.put("IS_ZUJUAN", "1");
            } else {
                column.put("IS_ZUJUAN", "0");
            }

            if (yqdaFolder.getFolderId() != null || yqdaFolder.getItemId() != null) {
                yqdaFolderMapper.addYqdaFolder(yqdaFolder);
            }
        }

        //验证特殊字符
        SpecialCharacter(category.getGroupId(), 0, column);

        column.putAll(addCommonCol(column, category, 0));

        //卷内件的密级不能大于卷的密级
        if (category.getType() == 1 || category.getType() == 3) {
            if (object.containsKey("folderId") && StringUtils.isNotEmpty(object.getString("folderId"))) {
                Long folderId = object.getLong("folderId");
                Boolean bl = verifyMJ(category, folderId, null, column.get("MJ"));
                if (bl == false) {
                    throw new ServiceException("卷内件的密级不能大于卷的密级！");
                }
            }
        }

        //电子文件密级不能大于件的密级
        if(FBswitch){
            /*String maxMJ = archiveMapper.getMaxMjDoc(category.getEfileTableName(),daId);
            if(StringUtils.isNotEmpty(maxMJ)){
                if(StringUtils.isEmpty(column.get("MJ"))){
                    throw new ServiceException("请填写档案密级！");
                }else {
                    Integer daMJ = Integer.valueOf(column.get("MJ"));  //档案密级
                    Integer docMJ = Integer.valueOf(maxMJ);  //文件密级
                    if(docMJ>daMJ){
                        throw new ServiceException("电子文件密级不能大于件密级！");
                    }
                }
            }*/
            //todo 电子文件密级不能大于件的密级
        }


        column.put("ID", String.valueOf(daId));
        TenantYqda yqda = new TenantYqda();
        yqda.setColNames(column);
        yqda.setTableName(category.getFileTableName());
        yqdaMapper.insertYqdaDisperse(yqda); //插入分表

        column.put("SUB_TABLE_NAME", category.getFileTableName());
        column.remove("ID");
        column.put("DA_ID", String.valueOf(daId));
        yqda.setColNames(column);
        yqda.setTableName(new TenantYqda().getTableName());
        int r = yqdaMapper.insertYqda(yqda); //插入总表
        //根据关联关系 修改操作
        if (object.containsKey("folderId") && StringUtils.isNotEmpty(object.getString("folderId"))) {
            List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(object.getString("folderId"), new TenantYqdaFolder().getTableName());
            relevanceMap(category, 1, object.getLong("folderId"), String.join(",", daIds));
        }
        if (category.getType() == 3) {
            List<String> folderIds = yqdaFolderMapper.selectFolderIdByFileId(String.valueOf(daId), new TenantYqdaFolder().getTableName());
            if (folderIds != null && folderIds.size() > 0) {
                List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(String.join(",", folderIds), category.getItemTableName(), new TenantItemFolder().getTableName());
                for (Long itemId : itemIds) {
                    List<String> folderIdStr = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId), new TenantItemFolder().getTableName());
                    relevanceMap(category, 3, itemId, String.join(",", folderIdStr));
                }
            }
        }
        /*if(FBswitch){//查看文件密级是否正确
            String daMj=column.get("MJ");
            if(null==daMj||"".equals(daMj)){
                throw new RuntimeException("档案密级为空!");
            }
            JSONObject docjson=new JSONObject(1<<2);
            docjson.put("categoryId",categoryId);
            docjson.put("daId",daId);
            docjson.put("fields","WJMJ,DOC_NAME");
            List<Map<String, Object>> documentlist = documentService.getDocumentBydaId(docjson);
            for (int i = 0; i < documentlist.size(); i++) {
                String wjmj=String.valueOf(documentlist.get(i).get("WJMJ"));
                if(null==wjmj||"".equals(wjmj)){
                    throw new RuntimeException("电子文件《"+documentlist.get(i).get("DOC_NAME")+"》的密级为空!");
                }
                if(Integer.parseInt(String.valueOf(wjmj))>Integer.parseInt(String.valueOf(daMj))){
                    throw new RuntimeException("电子文件《"+documentlist.get(i).get("DOC_NAME")+"》的密级大于档案密级!");
                }
            }
        }*/
        return r;
    }


    /**
     * 卷内件的密级不能大于卷的密级
     *
     * @param category
     * @param folderId
     * @param daId
     * @param daMJ
     * @return false 没有通过验证
     */
    private Boolean verifyMJ(TenantCategory category, Long folderId, Long daId, String daMJ) {
        //查询卷
        Map<String, Object> data = folderMapper.getYqFolderById("MJ", folderId, category.getFolderTableName());
        if (data != null && data.size() > 0 && data.get("MJ") != null && !"".equals(String.valueOf(data.get("MJ")))) {
            Integer folderMj = Integer.valueOf(String.valueOf(data.get("MJ")));
            //优先使用
            Integer mj = 0;
            if (daId != null) {
                Map<String, Object> daData = yqdaMapper.getYqdaById("MJ", daId, category.getFileTableName());
                if (daData != null && daData.size() > 0 && daData.get("MJ") != null && !"".equals(String.valueOf(daData.get("MJ")))) {
                    mj = Integer.valueOf(String.valueOf(daData.get("MJ")));
                } else {
                    return true;
                }
            } else if (StringUtils.isNotEmpty(daMJ)) {
                mj = Integer.valueOf(daMJ);
            } else {
                return true;
            }
            if (mj > folderMj) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    @Transactional
    public int updateItem(JSONObject object) {
        //{categoryId:111,id:'123',column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        JSONArray array = object.getJSONArray("column");
        Map<String, String> column = new HashMap<>();
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }

        //验证特殊字符
        SpecialCharacter(category.getGroupId(), 3, column);

        column.putAll(updateCommonCol(column, category));

        TenantYqItem item = new TenantYqItem();
        item.setColNames(column);

        item.setTableName(category.getItemTableName());
        item.setItemId(id);
        itemMapper.updateItemDisperse(item); //修改分表

        item.setTableName(new TenantYqItem().getTableName());
        int r = itemMapper.updateItem(item); //修改总表


        List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(id), new TenantItemFolder().getTableName());
        //更新项目
        relevanceMap(category, 3, id, String.join(",", folderIds));
        for (String folderId : folderIds) {
            //更新卷
            List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(folderId, new TenantYqdaFolder().getTableName());
            relevanceMap(category, 1, Long.valueOf(folderId), String.join(",", daIds));
        }

        return r;
    }

    @Override
    @Transactional
    public int updateFolder(JSONObject object) {
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        JSONArray array = object.getJSONArray("column");
        Map<String, String> column = new HashMap<>();
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        //特殊字符验证
        SpecialCharacter(category.getGroupId(), 1, column);

        column.putAll(updateCommonCol(column, category));

        //卷内件的密级不能大于卷的密级
        if (column.get("MJ") != null && !"".equals(column.get("MJ"))) {
            Integer juanMj = Integer.valueOf(column.get("MJ"));
            Integer jianMaxMj = yqdaMapper.getMaxJianMjByFolderIds(String.valueOf(id), category.getFileTableName(), new TenantYqdaFolder().getTableName());
            if (jianMaxMj != null && jianMaxMj > juanMj) {
                throw new ServiceException("卷内件的密级不能大于卷的密级");
            }

        }

        TenantYqFolder folder = new TenantYqFolder();
        folder.setColNames(column);

        folder.setTableName(category.getFolderTableName());
        folder.setFolderId(id);
        folderMapper.updateYqFolderDisperse(folder); //修改分表

        folder.setTableName(new TenantYqFolder().getTableName());
        int r = folderMapper.updateYqFolder(folder); //修改总表


        List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(String.valueOf(id), new TenantYqdaFolder().getTableName());
        //更新卷
        relevanceMap(category, 1, id, String.join(",", daIds));
        if (category.getType() == 3) {
            //更新项目
            List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(String.valueOf(id), category.getFolderTableName(), new TenantItemFolder().getTableName());
            if (itemIds.size() > 0) {
                List<String> folderIds = itemFolderMapper.selectFolderIdByItemId(String.valueOf(itemIds.get(0)), new TenantItemFolder().getTableName());
                relevanceMap(category, 3, itemIds.get(0), String.join(",", folderIds));
            }
        }
        return r;
    }

    @Override
    @Transactional
    public int updateYqda(JSONObject object) {
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        JSONArray array = object.getJSONArray("column");
        Map<String, String> column = new HashMap<>();
        for (int j = 0; j < array.size(); j++) {
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"), data.getString("value"));
        }
        //特殊字符验证
        SpecialCharacter(category.getGroupId(), 0, column);

        column.putAll(updateCommonCol(column, category));

        //卷内件的密级不能大于卷的密级
        /*if (category.getType() == 1 || category.getType() == 3) {
            //查询卷id
            Long folderId = yqdaFolderMapper.getFolderIdBydaId(id, new TenantYqdaFolder().getTableName());
            if (folderId != null) {
                Boolean bl = verifyMJ(category, folderId, null, column.get("MJ"));
                if (bl == false) {
                    throw new ServiceException("卷内件的密级不能大于卷的密级！");
                }
            }
        }*/

        TenantYqda yqda = new TenantYqda();
        yqda.setColNames(column);

        yqda.setTableName(category.getFileTableName());
        yqda.setDaId(id);
        yqdaMapper.updateYqdaDisperse(yqda); //修改分表

        yqda.setTableName(new TenantYqda().getTableName());
        int r = yqdaMapper.updateYqda(yqda); //修改总表

        //更新
        if (category.getType() == 1) {
            List<String> folderIds = yqdaFolderMapper.selectFolderIdByFileId(String.valueOf(id), new TenantYqdaFolder().getTableName());
            if (folderIds != null && folderIds.size() > 0&&folderIds.get(0)!=null) {
                List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(folderIds.get(0), new TenantYqdaFolder().getTableName());
                relevanceMap(category, 1, Long.valueOf(id), String.join(",", daIds));
            }
        }
        if (category.getType() == 3) {
            List<String> folderIds = yqdaFolderMapper.selectFolderIdByFileId(String.valueOf(id), new TenantYqdaFolder().getTableName());
            if (folderIds != null && folderIds.size() > 0) {
                List<Long> itemIds = itemFolderMapper.getItemIdByFolderId(String.join(",", folderIds), category.getFolderTableName(), new TenantItemFolder().getTableName());
                if (itemIds != null && itemIds.size() > 0) {
                    relevanceMap(category, 3, Long.valueOf(id), String.join(",", folderIds));
                }
            }

        }
        /*if(FBswitch){
            //判断文件密级
            JSONObject json=new JSONObject();
            json.put("categoryId",categoryId);
            json.put("daId",id);
            json.put("fields","DOC_NAME,WJMJ");
            List<Map<String, Object>> documentList = documentService.getDocumentBydaId(json);
            for (int i = 0; i < documentList.size(); i++) {
                String fileMj=String.valueOf(documentList.get(i).get("WJMJ"));
                if(null==fileMj||"".equals(fileMj)||"null".equals(fileMj)){
                    throw new RuntimeException("电子文件《"+documentList.get(i).get("DOC_NAME")+"》的密级为空!");
                }
                String daMj="";
                //可能修改了密级
                if(null==column.get("MJ")){
                    //未修改密级去数据库查
                    Map<String, Object> daInfo = yqdaMapper.getYqdaAllById("MJ", id, new TenantYqda().getTableName());
                    daMj=String.valueOf(daInfo.get("MJ"));
                    if("null".equals(daMj)||null==daMj){
                        throw new RuntimeException("档案密级为空!");
                    }
                }else{
                    daMj=column.get("MJ");
                }
                if(Integer.parseInt(fileMj)>Integer.parseInt(daMj)){
                    throw new RuntimeException("文件密级大于档案密级!");
                }
            }
        }*/
        return r;
    }

    @Override
    public Map<String, Object> getItemById(JSONObject object) {
        //{"categoryId":"123","id":"456","column":"TITLE,BGQX"}
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        String column = object.getString("column");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, Object> data = itemMapper.getItemById(column, id, category.getItemTableName());
        return data;
    }

    @Override
    public Map<String, Object> getFolderById(JSONObject object) {
        //{"categoryId":"123","id":"456","column":"TITLE,BGQX"}
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        String column = object.getString("column");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, Object> data = folderMapper.getYqFolderById(column, id, category.getFolderTableName());
        return data;
    }

    @Override
    public Map<String, Object> getYqdaById(JSONObject object) {
        //{"categoryId":"123","id":"456","column":"TITLE,BGQX"}
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("id");
        String column = object.getString("column");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, Object> data = yqdaMapper.getYqdaById(column, id, category.getFileTableName());
        return data;
    }

    /**
     * 接收
     *
     * @param categoryId
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int jieshou(Long categoryId, Long[] ids) {
        int r = 0;
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        Map<String, String> column = new HashMap<>();
        column.put("STATE", "2");
        //处理项目层
        if (category.getType() == 3) {
            for (int i = 0; i < ids.length; i++) {
                List<Long> daIds = yqdaFolderMapper.getDaIdNoFolderIdByItemId(ids[i].toString(), category.getFileTableName(), new TenantYqdaFolder().getTableName());
                if (daIds != null && daIds.size() > 0) {
                    throw new ServiceException("项目下存在关联的件没有组卷！");
                }
                Long[] id = new Long[]{ids[i]};
                Long[] idss = folderMapper.getFolderIdsByItemIds(id, category.getFolderTableName(), new TenantItemFolder().getTableName());//查询项目下的卷
                if (idss == null || idss.length == 0) {
                    throw new ServiceException("项目下存在没有卷信息，接收失败！");
                }
            }
            TenantYqItem item = new TenantYqItem();
            item.setColNames(column);
            itemMapper.updateItemByIds(item, ids); //主表
            item.setTableName(category.getItemTableName());
            r = itemMapper.updateItemDisperseByIds(item, ids);  //分表

            ids = folderMapper.getFolderIdsByItemIds(ids, category.getFolderTableName(), new TenantItemFolder().getTableName());//查询项目下的所有卷
        }
        //处理卷层
        if (category.getType() == 3 || category.getType() == 1) {
            /*for (int i = 0; i < ids.length; i++) {
                Long[] id = new Long[]{ids[i]};
                Long[] idss = yqdaMapper.getDaIdsByFolderIds(id,category.getFileTableName(),new TenantYqdaFolder().getTableName());//查询卷下的件
                if(idss== null || idss.length==0){
                    throw new ServiceException("卷下存在没有件信息，接收失败！");
                }
            }*/
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(column);
            folderMapper.updateYqFolderByIds(folder, ids); //主表
            folder.setTableName(category.getFolderTableName());
            r = folderMapper.updateYqFolderDisperseByIds(folder, ids);
            ids = yqdaMapper.getDaIdsByFolderIds(ids, category.getFileTableName(), new TenantYqdaFolder().getTableName());//查询卷下所有的件
        }
        //处理件层

        if (ids != null && ids.length > 0) {
            List<Long> longs = Arrays.asList(ids);
            List<List<Long>> lists = ListUtils.subList(longs, 5000);
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(column);
            for (int j = 0; j < lists.size(); j++) {
                List<Long> longs1 = lists.get(j);
                yqdaMapper.updateYqdaByIds2(yqda, longs1);
            }
            yqda.setTableName(category.getFileTableName());
            for (int i = 0; i < lists.size(); i++) {
                List<Long> longs1 = lists.get(i);
                r = yqdaMapper.updateYqdaDisperseByIds2(yqda, longs1);
            }
        }
        return r;
    }
    @Override
    @Transactional
    public int jieshou2(Long categoryId, Long[] ids) {
        int r = 0;
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        Map<String,String> column = new HashMap<>();
        column.put("STATE","10");
        //处理项目层
        if(category.getType() == 3){
            for (int i = 0; i < ids.length; i++) {
                List<Long> daIds = yqdaFolderMapper.getDaIdNoFolderIdByItemId(ids[i].toString(),category.getFileTableName(),new TenantYqdaFolder().getTableName());
                if(daIds !=null && daIds.size()>0){
                    throw new ServiceException("项目下存在关联的件没有组卷！");
                }
                Long[] id = new Long[]{ids[i]};
                Long [] idss = folderMapper.getFolderIdsByItemIds(id,category.getFolderTableName(),new TenantItemFolder().getTableName());//查询项目下的卷
                if(idss== null || idss.length==0){
                    throw new ServiceException("项目下存在没有卷信息，接收失败！");
                }
            }
            TenantYqItem item = new TenantYqItem();
            item.setColNames(column);
            itemMapper.updateItemByIds(item,ids); //主表
            item.setTableName(category.getItemTableName());
            r = itemMapper.updateItemDisperseByIds(item,ids);  //分表

            ids = folderMapper.getFolderIdsByItemIds(ids,category.getFolderTableName(),new TenantItemFolder().getTableName());//查询项目下的所有卷
        }
        //处理卷层
        if(category.getType() == 3 || category.getType() == 1){
            /*for (int i = 0; i < ids.length; i++) {
                Long[] id = new Long[]{ids[i]};
                Long[] idss = yqdaMapper.getDaIdsByFolderIds(id,category.getFileTableName(),new TenantYqdaFolder().getTableName());//查询卷下的件
                if(idss== null || idss.length==0){
                    throw new ServiceException("卷下存在没有件信息，接收失败！");
                }
            }*/
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(column);
            folderMapper.updateYqFolderByIds(folder,ids); //主表
            folder.setTableName(category.getFolderTableName());
            r = folderMapper.updateYqFolderDisperseByIds(folder,ids);
            ids = yqdaMapper.getDaIdsByFolderIds(ids,category.getFileTableName(),new TenantYqdaFolder().getTableName());//查询卷下所有的件
        }
        //处理件层

        if(ids !=null && ids.length>0){
            List<Long> longs = Arrays.asList(ids);
            List<List<Long>> lists = ListUtils.subList(longs, 5000);
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(column);
            for(int j=0;j<lists.size();j++){
                List<Long> longs1 = lists.get(j);
                yqdaMapper.updateYqdaByIds2(yqda,longs1);
            }
            yqda.setTableName(category.getFileTableName());
            for(int i=0;i<lists.size();i++){
                List<Long> longs1 = lists.get(i);
                r = yqdaMapper.updateYqdaDisperseByIds2(yqda,longs1);
            }
        }
        return r;
    }

    /**
     * 修改的公共字段
     *
     * @param map
     * @param category
     * @return
     */
    private Map<String, String> updateCommonCol(Map<String, String> map, TenantCategory category) {
        LoginUser user = SecurityUtils.getLoginUser();
        if (!map.containsKey("UPDATE_BY")) {
            map.put("UPDATE_BY", user.getUsername());
        }
        if (!map.containsKey("UPDATE_TIME")) {
            map.put("UPDATE_TIME", DateUtils.getTime());
        }
        /*if(category.getType() == 0 || category.getType() == 1){
            if(StringUtils.isNotEmpty(map.get("GDCS"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDCS"))).getData();
                map.put("GDCS",sysDept.getDeptName());
                map.put("GDCS_ID", String.valueOf(sysDept.getDeptId()));
            }
            if(StringUtils.isNotEmpty(map.get("GDSJ"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDSJ"))).getData();
                map.put("GDSJ",sysDept.getDeptName());
                map.put("GDSJ_ID", String.valueOf(sysDept.getDeptId()));
            }
        }*/
        return map;
    }

    /**
     * 添加公共列
     *
     * @param map
     * @return
     */
    private Map<String, String> addCommonCol(Map<String, String> map, TenantCategory category, Integer type) {

        //元数据中的默认值
        TenantMdataList mdataList = new TenantMdataList();
        mdataList.setType(type);
        List<TenantMdataList> tenantMdataLists = mdataListMapper.selectNotEmptyDefaultByCategoryId(mdataList, category.getId(), new TenantCategory().getTableName());
        for (TenantMdataList list : tenantMdataLists) {
            if (!map.containsKey(list.getFieldName())) {
                map.put(list.getFieldName(), list.getDefaultValue());
            }
        }

        LoginUser user = SecurityUtils.getLoginUser();
        if (!map.containsKey("STATE")) {
            /*1:预归档-未接收
            2:预归档-已接收
            3:数字化成果未接收
            4:归档审批中
            5:已归档
            6:移交审批中   --没用
            7:已移交      --没用
            8：已销毁
            9：预归档流程中
            10：预归档已完成
            11 档案征集
            12 接收管理
            13 移交包接收
            999:文书资料库*/
            map.put("STATE", "1");
        }
        if (!map.containsKey("JS_TYPE")) {
            /*0:离线接收
            1:在线接收
            2:档案接收
            3:档案征集
            4:接收管理*/
            map.put("JS_TYPE", "0");
        }
        if (!map.containsKey("CREATE_BY")) {
            map.put("CREATE_BY", user.getUsername());
        }
        if (!map.containsKey("CREATE_ID")) {
            map.put("CREATE_ID", String.valueOf(user.getUserId()));
        }
        if (!map.containsKey("CREATE_TIME")) {
            map.put("CREATE_TIME", DateUtils.getTime());
        }
        if (!map.containsKey("IS_INDEX")) {
            map.put("IS_INDEX", "0");
        }
        if (!map.containsKey("IS_DEL")) {
            map.put("IS_DEL", "0");
        }
        if (!map.containsKey("GDCS")) {
            map.put("GDCS", user.getSysUser().getDept().getDeptName());
            map.put("GDCS_ID", String.valueOf(user.getSysUser().getDept().getDeptId()));
        }/*else if(StringUtils.isNotEmpty(map.get("GDCS"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDCS"))).getData();
                map.put("GDCS",sysDept.getDeptName());
                map.put("GDCS_ID", String.valueOf(sysDept.getDeptId()));
            }*/
        if (type == 0 || type == 1) {
            if (!map.containsKey("GDSJ")) {
                map.put("GDSJ", user.getSysUser().getDept().getParentName());
                map.put("GDSJ_ID", String.valueOf(user.getSysUser().getDept().getParentId()));
            }/*else if(StringUtils.isNotEmpty(map.get("GDSJ"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDSJ"))).getData();
                map.put("GDSJ",sysDept.getDeptName());
                map.put("GDSJ_ID", String.valueOf(sysDept.getDeptId()));
            }*/
            if (!map.containsKey("QZH")) {
                map.put("QZH", category.getFondsCode());
            }
            if (!map.containsKey("TYPE")) {
                map.put("TYPE", category.getCode());
            }
        }


        return map;
    }

    /**
     * @param category
     * @param type
     * @param id       著录档案的id
     * @param ids      type = 3(项目) 时 ids是卷id
     *                 type = 1(卷) 时 ids是件id
     *                 type = 0(件)
     */
    @Override
    public void relevanceMap(TenantCategory category, Integer type, Long id, String ids) {
        TenantRelevance select = new TenantRelevance();
        select.setFieldLevel(type);
        select.setGroupId(category.getGroupId());
        List<TenantRelevance> list = cateMdataListMapper.getrelevancelist(select);
        if (list != null && list.size() > 0) {
            for (TenantRelevance relevance : list) {
                if (type == 3) { //著录项目
                    Map<String, String> data = new HashMap<>();
                    if (relevance.getRelefieldLevel() == 3) {
                        if (relevance.getRelation() == 0) {  //等于关系
                            Map<String, Object> itemData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getItemTableName());
                            if (itemData != null && itemData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(itemData.get(relevance.getFieldName())))) {
                                data.put(relevance.getReleField(), String.valueOf(itemData.get(relevance.getFieldName())));
                            }
                        }
                    } else if (relevance.getRelefieldLevel() == 1) { //关联卷层
                        if (StringUtils.isNotEmpty(ids)) {
                            if (relevance.getRelation() == 0) {  //等于关系
                                Map<String, Object> itemData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getItemTableName());
                                if (itemData != null && itemData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(itemData.get(relevance.getFieldName())))) {
                                    data.put(relevance.getReleField(), String.valueOf(itemData.get(relevance.getFieldName())));
                                }
                            } else if (relevance.getRelation() == 5) {  //COUNT关系
                                int countData = archiveMapper.getCOUNTData(ids, category.getFolderTableName());
                                data.put(relevance.getFieldName(), String.valueOf(countData));
                            } else if (relevance.getRelation() == 6) {  //SUM关系
                                int sumData = archiveMapper.getSUMData(YqDatabaseSQLUtil.YQ_ISNULL("SUM(" + relevance.getReleField() + ")", "0"), ids, category.getFolderTableName());
                                data.put(relevance.getFieldName(), String.valueOf(sumData));
                            }
                        } else {
                            if (relevance.getRelation() == 5) {  //COUNT关系
                                int countData = 0;
                                data.put(relevance.getFieldName(), String.valueOf(countData));
                            } else if (relevance.getRelation() == 6) {  //SUM关系
                                int sumData = 0;
                                data.put(relevance.getFieldName(), String.valueOf(sumData));
                            }
                        }
                    } else if (relevance.getRelefieldLevel() == 0) { //关联件层
                        if (StringUtils.isNotEmpty(ids)) {
                            //所有卷下的件
                            List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(ids, new TenantYqdaFolder().getTableName());
                            if (daIds != null && daIds.size() > 0) {
                                if (relevance.getRelation() == 0) {  //等于关系
                                    Map<String, Object> itemData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getItemTableName());
                                    if (itemData != null && itemData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(itemData.get(relevance.getFieldName())))) {
                                        data.put(relevance.getReleField(), String.valueOf(itemData.get(relevance.getFieldName())));
                                    }
                                } else if (relevance.getRelation() == 5) {  //COUNT关系
                                    int countData = archiveMapper.getCOUNTData(String.join(",", daIds), category.getFileTableName());
                                    data.put(relevance.getFieldName(), String.valueOf(countData));
                                } else if (relevance.getRelation() == 6) {  //SUM关系
                                    int sumData = archiveMapper.getSUMData(YqDatabaseSQLUtil.YQ_ISNULL("SUM(" + relevance.getReleField() + ")", "0"), String.join(",", daIds), category.getFileTableName());
                                    data.put(relevance.getFieldName(), String.valueOf(sumData));
                                }
                            } else {
                                //卷下没有件直接赋值为0
                                if (relevance.getRelation() == 5) {  //COUNT关系
                                    data.put(relevance.getFieldName(), "0");
                                } else if (relevance.getRelation() == 6) {  //SUM关系
                                    data.put(relevance.getFieldName(), "0");
                                }
                            }
                        } else {
                            //卷下没有件直接赋值为0
                            if (relevance.getRelation() == 5) {  //COUNT关系
                                data.put(relevance.getFieldName(), "0");
                            } else if (relevance.getRelation() == 6) {  //SUM关系
                                data.put(relevance.getFieldName(), "0");
                            }
                        }
                    }
                    if (data.size() > 0) {
                        if (relevance.getRelefieldLevel() == 3) {
                            TenantYqItem yqItem = new TenantYqItem();
                            yqItem.setItemId(id);
                            yqItem.setColNames(data);
                            itemMapper.updateItem(yqItem);
                            yqItem.setTableName(category.getItemTableName());
                            itemMapper.updateItemDisperse(yqItem);
                        } else if (relevance.getRelation() == 0) {
                            //等于关系 最终修改的是卷层或者件层
                            if (StringUtils.isNotEmpty(ids)) {
                                String[] folderIds = ids.split(",");
                                if (relevance.getRelefieldLevel() == 1) {
                                    for (String folderId : folderIds) {
                                        TenantYqFolder yqFolder = new TenantYqFolder();
                                        yqFolder.setFolderId(Long.valueOf(folderId));
                                        yqFolder.setColNames(data);
                                        folderMapper.updateYqFolder(yqFolder);
                                        yqFolder.setTableName(category.getFolderTableName());
                                        folderMapper.updateYqFolderDisperse(yqFolder);
                                    }
                                } else if (relevance.getRelefieldLevel() == 0) {
                                    for (String folderId : folderIds) {
                                        List<String> daIds = yqdaFolderMapper.selectFileIdByFolderId(folderId, new TenantYqdaFolder().getTableName());
                                        for (String daId : daIds) {
                                            TenantYqda yqda = new TenantYqda();
                                            yqda.setDaId(Long.valueOf(daId));
                                            yqda.setColNames(data);
                                            yqdaMapper.updateYqda(yqda);
                                            yqda.setTableName(category.getFileTableName());
                                            yqdaMapper.updateYqdaDisperse(yqda);
                                        }
                                    }
                                }
                            }
                        } else if (relevance.getRelation() == 5 || relevance.getRelation() == 6) {  //COUNT关系；SUM关系 修改的是项目层
                            TenantYqItem yqItem = new TenantYqItem();
                            yqItem.setItemId(id);
                            yqItem.setColNames(data);
                            itemMapper.updateItem(yqItem);
                            yqItem.setTableName(category.getItemTableName());
                            itemMapper.updateItemDisperse(yqItem);
                        }

                    }
                } else if (type == 1) { //著录卷
                    Map<String, String> data = new HashMap<>();
                    if (relevance.getRelefieldLevel() == 1) {
                        if (relevance.getRelation() == 0) {
                            Map<String, Object> archiveData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getFolderTableName());
                            if (archiveData != null && archiveData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(archiveData.get(relevance.getFieldName())))) {
                                data.put(relevance.getReleField(), String.valueOf(archiveData.get(relevance.getFieldName())));
                            }
                        }
                    } else if (relevance.getRelefieldLevel() == 0) {
                        if (StringUtils.isNotEmpty(ids)) {
                            if (relevance.getRelation() == 0) {  //等于关系
                                Map<String, Object> archiveData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getFolderTableName());
                                if (archiveData != null && archiveData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(archiveData.get(relevance.getFieldName())))) {
                                    data.put(relevance.getReleField(), String.valueOf(archiveData.get(relevance.getFieldName())));
                                }
                            } else if (relevance.getRelation() == 5) {  //COUNT关系
                                int countData = archiveMapper.getCOUNTData(ids, category.getFileTableName());
                                data.put(relevance.getFieldName(), String.valueOf(countData));
                            } else if (relevance.getRelation() == 6) {  //SUM关系
                                int sumData = archiveMapper.getSUMData(YqDatabaseSQLUtil.YQ_ISNULL("SUM(" + relevance.getReleField() + ")", "0"), ids, category.getFileTableName());
                                data.put(relevance.getFieldName(), String.valueOf(sumData));
                            }
                        } else {
                            if (relevance.getRelation() == 5) {  //COUNT关系
                                data.put(relevance.getFieldName(), "0");
                            } else if (relevance.getRelation() == 6) {  //SUM关系
                                data.put(relevance.getFieldName(), "0");
                            }
                        }
                    }
                    if (data.size() > 0) {
                        if (relevance.getRelefieldLevel() == 1) {
                            TenantYqFolder yqFolder = new TenantYqFolder();
                            yqFolder.setFolderId(id);
                            yqFolder.setColNames(data);
                            folderMapper.updateYqFolder(yqFolder);
                            yqFolder.setTableName(category.getFolderTableName());
                            folderMapper.updateYqFolderDisperse(yqFolder);
                        } else {
                            if (relevance.getRelation() == 0) {
                                if (StringUtils.isNotEmpty(ids) && relevance.getRelefieldLevel() == 0) {
                                    String[] daIds = ids.split(",");
                                    for (String daId : daIds) {
                                        TenantYqda yqda = new TenantYqda();
                                        yqda.setDaId(Long.valueOf(daId));
                                        yqda.setColNames(data);
                                        yqdaMapper.updateYqda(yqda);
                                        yqda.setTableName(category.getFileTableName());
                                        yqdaMapper.updateYqdaDisperse(yqda);
                                    }
                                }
                            } else if (relevance.getRelation() == 5 || relevance.getRelation() == 6) {
                                TenantYqFolder yqFolder = new TenantYqFolder();
                                yqFolder.setFolderId(id);
                                yqFolder.setColNames(data);
                                folderMapper.updateYqFolder(yqFolder);
                                yqFolder.setTableName(category.getFolderTableName());
                                folderMapper.updateYqFolderDisperse(yqFolder);
                            }
                        }
                    }
                } else if (type == 0) { //著录件
                    Map<String, String> data = new HashMap<>();
                    if (relevance.getRelefieldLevel() == 1) {
                        if (relevance.getRelation() == 0) {
                            Map<String, Object> archiveData = archiveMapper.getArchiveDataById(relevance.getFieldName(), id, category.getFileTableName());
                            if (archiveData != null && archiveData.get(relevance.getFieldName()) != null && !"".equals(String.valueOf(archiveData.get(relevance.getFieldName())))) {
                                data.put(relevance.getReleField(), String.valueOf(archiveData.get(relevance.getFieldName())));
                            }
                        }
                    }
                    if (data.size() > 0) {
                        TenantYqda yqda = new TenantYqda();
                        yqda.setDaId(id);
                        yqda.setColNames(data);
                        yqdaMapper.updateYqda(yqda);
                        yqda.setTableName(category.getFileTableName());
                        yqdaMapper.updateYqdaDisperse(yqda);
                    }
                    /*Map<String,Object> archiveData = archiveMapper.getArchiveDataById(relevance.getFieldName(),id,category.getFileTableName());
                    Map<String,String> data = new HashMap<>();
                    if(archiveData != null){
                        TenantYqdaFolder yqdaFolder = yqdaFolderMapper.selectByDaId(id,new TenantYqdaFolder().getTableName());  //关联关系
                        if(yqdaFolder !=null){
                            if(relevance.getRelefieldLevel() == 3){
                                if(yqdaFolder.getItemId()!=null){
                                    List<Object> itemData = archiveMapper.getDataDistinct(relevance.getReleField(),String.valueOf(yqdaFolder.getItemId()),category.getItemTableName());
                                    if(itemData !=null && itemData.size() == 1){ //等于关系
                                        data.put(relevance.getFieldName(),itemData.get(0).toString());
                                    }
                                }
                            }else if(relevance.getRelefieldLevel() == 1){
                                if(yqdaFolder.getFolderId()!=null){
                                    List<Object> folderData = archiveMapper.getDataDistinct(relevance.getReleField(),String.valueOf(yqdaFolder.getFolderId()),category.getFolderTableName());
                                    if(folderData !=null && folderData.size() == 1){ //等于关系
                                        data.put(relevance.getFieldName(),folderData.get(0).toString());
                                    }
                                }
                            }
                        }
                    }
                    if(data.size()>0){
                        TenantYqda yqda = new TenantYqda();
                        yqda.setDaId(id);
                        yqda.setColNames(data);
                        yqdaMapper.updateYqda(yqda);
                        yqda.setTableName(category.getFileTableName());
                        yqdaMapper.updateYqdaDisperse(yqda);
                    }*/
                }
            }
        }
    }

    @Override
    public String changeFileMj(Long daId, Long categoryId, Long docId, String mj) {
        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        Integer daMj=0;
        Integer fileMj=0;
        if(FBswitch){//不需要的话,随意修改
            if(null==mj||"".equals(mj)){
                return "文件密级为空!";
            }
            //判断文件密级是不是大于档案密级
            //获取档案密级
            Map<String, Object> da = archiveMapper.getArchiveDataById("MJ", daId, category.getFileTableName());
            /*if(null==da||da.isEmpty()){
                return "档案尚未保存或档案密级为空,无法修改!";
            }
            daMj=Integer.parseInt(String.valueOf(da.get("MJ")));
            fileMj=Integer.parseInt(String.valueOf(mj));
            if(fileMj>daMj){
                return "文件密级大于档案密级!";
            }*/
            if(da !=null && !da.isEmpty()){
                daMj=Integer.parseInt(String.valueOf(da.get("MJ")));
                fileMj=Integer.parseInt(mj);
                JSONObject object = new JSONObject();
                object.put("daMj",daMj);
                JSONArray array = new JSONArray();
                array.add(fileMj);
                object.put("wjMjs",array);
                String isOk = iTenantMijiComparisonTableService.determine(object);
                if(!isOk.equals("ok")){
                    return isOk;
                }
            }



        }
        //JSONObject json=new JSONObject();
        //json.put("categoryId",categoryId);
        //json.put("docId",docId);
        Map map=new HashMap(1<<1);
        map.put("MJ",mj);
        //JSONArray array=new JSONArray(1);
        //array.add(map);
        //json.put("column",array);
        //documentService.updateDocument(json);


        TenantYqdaDocument document = new TenantYqdaDocument();
        document.setColNames(map);
        document.setDocId(docId);
        document.setTableName(category.getEfileTableName());
        int r = documentMapper.updateDocument(document);

        return "成功!";
    }

    /**
     * 验证非法字符
     * NormalCharacter 是可以允许输入的字符
     * \u4E00-\u9FA5a-zA-Z0-9  大小写字母数字中文
     * SpecialCharacter 其他被允许的字符
     *
     * @param groupId
     * @param type
     * @param data
     */
    private void SpecialCharacter(Long groupId, Integer type, Map<String, String> data) {
        String normalCharacter = sysConfigService.selectConfigByKey("NormalCharacter");
        if (StringUtils.isNotEmpty(normalCharacter)) {
            normalCharacter = normalCharacter.replaceAll("\\[", "").replaceAll("]", "");
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setGroupId(groupId);
            mdataList.setType(type);
            List<TenantMdataList> specialCharacter = mdataListMapper.selectSpecialCharacter(mdataList);
            String pattern = "";
            for (Map.Entry<String, String> entry : data.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Boolean zzkh = false, yzkh = false, fxg = false, zkh = false, ykh = false, fh = false;
                if (StringUtils.isNotEmpty(value)) {
                    Boolean isExist = false;
                    String name = "";
                    if (specialCharacter != null && specialCharacter.size() > 0) {
                        for (TenantMdataList mdata : specialCharacter) {
                            if (key.equals(mdata.getFieldName())) {
                                isExist = true;
                                String pat = mdata.getSpecialCharacter();
                                if (pat.indexOf("[") > -1) {
                                    zzkh = true;
                                }
                                if (pat.indexOf("]") > -1) {
                                    yzkh = true;
                                }
                                if (pat.indexOf("\\") > -1) {
                                    fxg = true;
                                }
                                if (pat.indexOf("(") > -1) {
                                    zkh = true;
                                }
                                if (pat.indexOf(")") > -1) {
                                    ykh = true;
                                }
                                if (pat.indexOf(";") > -1) {
                                    fh = true;
                                }
                                pat = normalCharacter + pat.replaceAll("\\[", "")
                                        .replaceAll("]", "")
                                        .replaceAll("\\\\", "")
                                        .replaceAll("\\(", "")
                                        .replaceAll("\\)", "")
                                        .replaceAll(";", "");
                                pattern = "[" + pat + "]+";
                                name = mdata.getFieldCaption();
                                break;
                            }
                        }
                    }
                    if (zzkh && value.indexOf("[") > -1) {
                        value = value.replaceAll("\\[", "");
                    }
                    if (yzkh && value.indexOf("]") > -1) {
                        value = value.replaceAll("]", "");
                    }
                    if (fxg && value.indexOf("\\") > -1) {
                        value = value.replaceAll("\\\\", "");
                    }
                    if (zkh && value.indexOf("(") > -1) {
                        value = value.replaceAll("\\(", "");
                    }
                    if (ykh && value.indexOf(")") > -1) {
                        value = value.replaceAll("\\)", "");
                    }
                    if (fh && value.indexOf(";") > -1) {
                        value = value.replaceAll(";", "");
                    }
                    if (!isExist) {
                        //没有元数据方案的配置就使用默认
                        pattern = "[" + normalCharacter + "]+";
                    }
                    // 创建Pattern对象
                    Pattern regex = Pattern.compile(pattern);
                    // 创建Matcher对象
                    Matcher matcher = regex.matcher(value);
                    // 检查是否匹配到特殊字符
                    if (!matcher.matches()) {
                        throw new ServiceException(name + "存在非法字符！");
                    }
                }
            }
        }

    }

}
